package com.jetpack.jetpacknavtest

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.Navigation
import com.jetpack.jetpacknavtest.databinding.Fragment2Binding
import kotlinx.android.synthetic.main.fragment_2.*

/**
 * A simple [Fragment] subclass.
 */
class Fragment2 : Fragment() {
    lateinit var myViewModel: MyViewModel
    lateinit var mBinding: Fragment2Binding

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {

        mBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_2, container, false)
        return mBinding.root
    }


    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        Log.e("fragment", "2")
        go.setOnClickListener {
            val action = Fragment2Directions.actionFragment2ToFragment21("likan", 10)
            Navigation.findNavController(it).navigate(action)
        }

        back.setOnClickListener {

//            popBackStack() 如果当前的返回栈是空的就会报错，因为栈是空的了，navigateUp() 则不会，还是停留在当前界面
            Navigation.findNavController(it).navigateUp()
//            Navigation.findNavController(it).popBackStack()
        }


        add.setOnClickListener {
            myViewModel.add()
        }

        // fragment 持有自己的
//        myViewModel = ViewModelProvider(this, ViewModelProvider.AndroidViewModelFactory.getInstance(activity!!.application)).get(MyViewModel::class.java)

       // activity 持有的 viewmodel
        myViewModel = ViewModelProvider(activity!!, ViewModelProvider.AndroidViewModelFactory.getInstance(activity!!.application)).get(MyViewModel::class.java)
        mBinding.viewmodel = myViewModel
        mBinding.lifecycleOwner = activity

    }

}
